package com.skb.task.service.impl;

import com.skb.task.mapper.TaskMapper;
import com.skb.task.pojo.Project;
import com.skb.task.pojo.Task;
import com.skb.task.service.TaskService;
import com.skb.task.util.pojo.QdResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author 沈楷博
 * @Company 永遠快樂
 * @Description
 * @Time 2024/9/10 下午4:38
 */
@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskMapper taskMapper;
    @Override
    public QdResult list(Task task,String projectId, Long parentId) {

        return QdResult.success(taskMapper.selectList(task,projectId,parentId));
    }
    @Override
    public QdResult save(Task task) {

        task.setTaskStatus(1);
        task.setTaskParent(2);
        task.setCreateTime(new Date());
        task.setModifyTime(new Date());
        int i = taskMapper.insertTask(task);
        // 判断当前任务是否有父级任务
        if(i == 1 && !task.getTaskParentId().equals(new Long(0))){
            // 查询父级任务
            Task parentTask = taskMapper.selectById(task.getTaskParentId());
            // 判断父级任务的parent是否是1
            if(parentTask.getTaskParent().equals(new Integer(2))){
                parentTask.setTaskParent(1);
                taskMapper.updateById(parentTask);
            }
        }
        return i == 1?QdResult.success(task):QdResult.error();
    }

    @Override
    public QdResult queryById(Long taskId) {
        return QdResult.success(taskMapper.selectById(taskId));
    }

    @Override
    public QdResult update(Task task) {
        taskMapper.updateById(task);
        return QdResult.success();
    }

    @Override
    public QdResult deleteTask(Task task) {

        long taskId = task.getTaskId();
        long taskParentId = task.getTaskParentId();
        if(taskParentId!=0){
            List<Task> tasks = this.selectByParentId(taskParentId,taskId);
            if(tasks.size()==0){
                taskMapper.noSonModifyParentById(taskParentId);
            }
        }

        taskMapper.delete(task);

        return QdResult.success();
    }

    @Override
    public List<Task> selectByParentId(long taskParentId, long taskId) {
        List<Task> tasks =taskMapper.selectByParentId(taskParentId,taskId);
        return tasks;
    }

    @Override
    public QdResult deletesTask(String[] taskIds) {
        List<String> idsList = Arrays.asList(taskIds);
        for (String taskId : idsList) {
            Long taskIdLong = Long.parseLong(taskId);
            Task task = new Task();
            task.setTaskId(taskIdLong);
            Task task1 = taskMapper.selectById(Long.valueOf(taskId));
            if (task1.getTaskParent() == 1 ) {
                    return QdResult.error("删除失败，任务包含子任务");
            }
            taskMapper.delete(task);
        }
        return QdResult.success();
    }
}